package org.lep.leetcode.datastructure.heap;

import java.util.PriorityQueue;

/**
 * https://leetcode-cn.com/problems/kth-largest-element-in-a-stream
 *
 * @author lverpeng
 * @since 2020/3/10
 */
public class KthLargest {
    private PriorityQueue<Integer> queue;
    private int size;

    public KthLargest(int k, int[] nums) {
        queue = new PriorityQueue<>(k);
        size = k;
        for (int i = 0; i < nums.length; i++) {
            add(nums[i]);
        }
    }

    /**
     * 添加新元素的时候维护一个固定大小的最小堆
     * 下面这种方式if条件划分的范围不清晰，add1的代码更加简洁
     * @param val
     * @return
     */
    public int add(int val) {
        if (queue.isEmpty()) {
            queue.add(val);
            return val;
        }
        if (queue.size() == size) {
            int num = queue.peek();
            if (val <= num) {
                return num;
            }
            queue.remove(num);
        }
        queue.add(val);

        return queue.peek();
    }

    public int add1(int val) {
        if (queue.size() < size) {
            queue.add(val);
            return val;
        }
        if (queue.peek() < val) {
            queue.remove();
            queue.add(val);
        }
        return queue.peek();
    }
}
